//
//  KAAdvance.swift
//  kano
//
//  Created by Frank on 2024/11/26.
//

import AAILivenessUI
import CryptoSwift
import Alamofire
import SwiftyJSON


class KAAdvance: NSObject {
    
    var applyModel: KAApply?
    var basicModel: KABasic?
    var retryCount = 0

    
    static let shared = KAAdvance()
    
    private override init() {
        super.init()
        initSDK()
    }
    
    private func initSDK() {
        
        // Init SDK Nigeria没有Global服务，不能设置为true
        AAILivenessSDK.initWith(.nigeria, isGlobalService: false)

        // Configure SDK
        AAILivenessSDK.configResultPictureSize(300)
        
        // Set whether to detect face occlusion. The default value is NO.
        AAILivenessSDK.configDetectOcclusion(true)
        
        let additionalConfig = AAILivenessSDK.additionalConfig();
        // Set the color of the round border in the avatar preview area. Default is clear color.
//        additionalConfig.roundBorderColor = UIColor(red: 0.36, green: 0.768, blue: 0.078, alpha: 1)
        
        // Set the color of the ellipse dashed line that appears during the liveness detection. Default is white color.
//        additionalConfig.ellipseLineColor = .green
        
        // Set the level of liveness detection. Default is AAIDetectionLevelNormal.
        // Available levels are AAIDetectionLevelEasy, AAIDetectionLevelNormal, AAIDetectionLevelHard
        // The harder it is, the stricter the verification is.
        additionalConfig.detectionLevel = .normal;
        
        
//        getAccessToken()
    }
    
    func setData(model: KAApply?, basic: KABasic?) {
        applyModel = model
        basicModel = basic
    }
    //获取活体token
    func getAccessToken() {
        UIViewController.ka_current().view.showLoading()

        let paramDic: [String : Any] = [
            "taskId": applyModel?.creditElement?.pageElements?.first?.taskId ?? ""
        ]
        applyProvider.request(.license(paramDic)) { [self] result in
            UIViewController.ka_current().view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    guard let responseString = String(data: response.data, encoding: .utf8) else {
                        return
                    }
                    let jsonData = JSON(parseJSON: responseString)
                    guard let dictionary = jsonData.dictionaryObject else {
                        return
                    }
                    guard let data = dictionary["data"] as? [String : Any] else {
                        return
                    }
                    guard let license = data["fieldforliveness"] as? String else {
                        return
                    }
                    self.ka_checkLicenseAndShowSDK(license: license)
                    
                }else {
                    UIViewController.ka_current().view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
    func ka_checkLicenseAndShowSDK(license: String) {
        let checkResult = AAILivenessSDK.configLicenseAndCheck(license)
        if checkResult == "SUCCESS" {
            // license is valid, show SDK page
            self.showSDK()
        } else if checkResult == "LICENSE_EXPIRE" {
            print("LICENSE_EXPIRE: please call your server's api to generate a new license")
        } else if checkResult == "APPLICATION_ID_NOT_MATCH" {
            print("APPLICATION_ID_NOT_MATCH: please bind your app's bundle identifier on our cms website, then recall your server's api to generate a new license")
        } else {
            print("\(checkResult)")
        }
    }
    
    func showSDK() {
        let vc = AAILivenessViewController()
        vc.recordUserGiveUp = true
        vc.language = "en"//"zh-Hans"
        vc.tapBackBtnAction()
        vc.detectionSuccessBlk = {(rawVC, result) in
            let livenessId = result.livenessId
            let bestImg = result.img
            let size = bestImg.size
            print(">>>>>Success Result: \(livenessId), imgSize: \(size.width), \(size.height)")
            //request our Api post livenessId
            self.applyModel?.creditElement?.livenessId = livenessId
            let vc = KAAdvanceSuccess(model: self.applyModel, basic: self.basicModel)
            rawVC.navigationController?.pushViewController(vc, animated: true)
            
            self.cacheResult()
            self.livenessResult()
        }
//        vc.detectionFailedBlk =  {rawVC, errorInfo in
//            var result: AAILivenessFailedResult = AAILivenessFailedResult(errorInfo: errorInfo)
//            // Get eventId(You should save this ID in case of tracking problems).
//            var eventId: String = result.eventId;
//            
//            NSLog("Detection failed: %@, message: %@, transactionId: %@, eventId: %@", result.errorCode, result.errorMsg, result.transactionId, eventId);
//        }
        vc.detectionFailedBlk = { rawVC, errorInfo in
            print(">>>>>errorInfo: \(errorInfo["key"] ?? "")")
            let errorKey = errorInfo["key"] as? String
            let errorId = errorInfo["eventId"] as? String

            var btnInfo = KABtnInfo(eleId: "sx_acb_livenessFail", pageId: "sx_acv_idcard", clickTime: Date.ka_currentData())
            var data = btnInfo.kj.JSONObject()
            data["adKey"] = errorKey
            data["adEventId"] = errorId
            KAReport.ka_reportWith(type: .btn, data: data)
            
            let maxRetryCount = Int(self.applyModel?.creditElement?.liveCreditFailNum ?? "0")
            self.retryCount += 1
            
            guard let key = errorInfo["key"] as? String else {return}
            //用户点击了左上返回按钮
            if key == "user_give_up" {
                rawVC.navigationController?.popViewController(animated: true)
                return
            }
            if self.retryCount < maxRetryCount ?? 0 {
                let vc = KAAdvanceFail(model: self.applyModel, basic: self.basicModel)
                rawVC.navigationController?.pushViewController(vc, animated: true)
            }
            else {
                //如果次数达到后台配置上限仍未识别成功，放弃活体识别直接去备用联系人
                let vc = KAContactVC(model: self.applyModel!)
                vc.var_basicModel = self.basicModel
                UIViewController.ka_current().navigationController?.pushViewController(vc, animated: true)
            }
        }
        vc.cameraPermissionDeniedBlk = { rawVC in
            rawVC.navigationController?.popViewController(animated: true)
            return
        }
        UIViewController.ka_current().navigationController!.pushViewController(vc, animated: true)
        
    }
    
    func cacheResult() {
        //将livenessId缓存到Basic回显数据中
        var basicDic = basicModel?.kj.JSONObject()
        //livenessId
        basicDic?["livenessId"] = self.applyModel?.creditElement?.livenessId
        let cacheDic: [String : Any] = [
            "userGid" : KAUserManager.shared.user.userGid,
            "loanStatementList" : "idcard",
            "value" : basicDic?.jsonString() ?? ""
        ]
        applyProvider.request(.cache(cacheDic)) { [self] result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAContent>.handleResponseData(response.data) { isSuccess, message, response in
                    }
                }else {
                    UIViewController.ka_current().view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    //调用活体查询结果，将本次流程的活体id和taskId传给大数据；因为livenessId有有效期，防止用户未在livenessId有效期内总提交授信；
    func livenessResult() {
        let paramDic: [String : Any] = [
            "taskId": applyModel?.creditElement?.pageElements?.first?.taskId ?? "",
            "livenessId": applyModel?.creditElement?.livenessId ?? ""
        ]
        applyProvider.request(.livenessResult(paramDic)) { [self] result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    guard let responseString = String(data: response.data, encoding: .utf8) else {
                        return
                    }
                    let jsonData = JSON(parseJSON: responseString)
                    guard let dictionary = jsonData.dictionaryObject else {
                        return
                    }
                    
                }else {
                    UIViewController.ka_current().view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
}

//测试流程用的测试接口
//extension KAAdvance {
//    func getAccessToken() {
//        var token = ""
//        
//        let accessKey = "28f9d6c2d2abe218"
//        let secretKey = "1fa8beddcddcfcae"
//        var timestamp = Date.ka_currentData()
//        var signature = accessKey + secretKey + timestamp
//        let signatureData = signature.data(using: .utf8)
//        let hash = signatureData!.sha256()
//        let hashString = hash.map { String(format: "%02hhx", $0) }.joined()
//        print("SHA-256 Hash: \(hashString)")
//        
//        let paraDic = [
//            "accessKey":accessKey,
//            "signature":hashString,
//            "timestamp":timestamp,
//            "periodSecond":3600
//        ] as [String : Any]
//        AF.request("https://nga-api.advance.ai/openapi/auth/ticket/v1/generate-token", method: .post, parameters: paraDic, encoding: JSONEncoding.default)
//            .responseJSON { response in
//                switch response.result {
//                case .success(let value):
//                    print("Response Data: \(value)")
//                    let content = value as? [String : Any]
//                    if let data = content!["data"] as? [String : Any] {
//                        let token = data["token"]! as! String
//                        
//                        self.getLicense(token: token)
//                    }
//                case .failure(let error):
//                    print("Error: \(error)")
//                }
//            }
//    }
//    
//    func getLicense(token: String) {
//        let paraDic = [
//            "licenseEffectiveSeconds":600,
//            "applicationId":"minos.pay.nominikash"
//        ] as [String : Any]
//        
//        let headers: HTTPHeaders = [
//            "X-ACCESS-TOKEN": token
//        ]
//        
//        AF.request("https://nga-api.advance.ai/nga/openapi/face-identity/v1/auth-license", method: .post, parameters: paraDic, encoding: JSONEncoding.default, headers: headers)
//            .responseJSON { response in
//                switch response.result {
//                case .success(let value):
//                    print("Response Data: \(value)")
//                    let content = value as? [String : Any]
//                    if let data = content!["data"] as? [String : Any] {
//                        let license = data["license"]! as! String
//                        print(">>>>>>>>license: \(license)")
//                        self.ka_checkLicenseAndShowSDK(license: license)
//                    }
//                case .failure(let error):
//                    print("Error: \(error)")
//                }
//            }
//        
//    }
//}
